package cn.jiyun.order.controller;

import cn.jiyun.common.vo.CommonResult;
import cn.jiyun.model.Order;
import cn.jiyun.model.dto.OrderDto;
import cn.jiyun.order.service.OrderService;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;


import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.spring.web.json.Json;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;

@RestController // 表示该类是一个RESTful API控制器
@RequestMapping("/api/order") // 为类设置统一的请求前缀
public class OrderController {
    @Autowired // 自动注入OrderService实例
    private OrderService orderService;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;


    /**
     * 查询并返回所有订单信息
     *
     * @return 返回订单列表
     */
   @RabbitListener(queues = "simple777.queue")
    @RabbitHandler
    public void receiveMessage(String msg, Channel channel, Message messages) {
        System.out.println("收到消息");
       HashMap<String,String> hashMap = JSON.parseObject(msg, HashMap.class);
       String s1 = hashMap.get("mid");
        Boolean redisMqPay = redisTemplate.opsForSet().isMember("redisMqPay", s1 + "");
        if (redisMqPay) {
            System.out.println("重复支付");
        } else {
            System.out.println("第一次支付");
            String s = hashMap.get("out_trade_no");
            LambdaQueryWrapper<Order> orderLambdaQueryWrapper = new LambdaQueryWrapper<>();
            orderLambdaQueryWrapper.eq(Order::getOrderId, s);
            Order order = orderService.getOne(orderLambdaQueryWrapper);
            order.setStatus(2);
            order.setPayId(hashMap.get("trade_no"));
            order.setPayTime(LocalDateTime.now());
            orderService.updateById(order);
            redisTemplate.opsForSet().add("redisMqPay", s1 + "", msg);
        }
    }
    @PostMapping("/submitYourOrder")
    public CommonResult submitYourOrder(@RequestBody OrderDto orderDto){
        if (orderService.validToken(orderDto.getToken(),"123456")){
            return  orderService.submitYourOrder(orderDto);
        }
        return CommonResult.error("请勿一直点");
    }
    @GetMapping("/tokenFindAll")
    public String tokenFindAll(){
        return   orderService.tokenFindAll();
    }
    @GetMapping("/paymentFeatures")
    public  CommonResult paymentFeatures(Integer userId){
        return  orderService.paymentFeatures(userId);
    }
}

